//
//  MNDInvestmentRecordViewController.m
//  minidai
//
//  Created by 容贤郁 on 2017/5/11.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDInvestmentRecordViewController.h"
#import "MNDInvestmentRecordListContainerViewController.h"
#import "MNDInvestmentRecordListViewController.h"
#import "MNDUserTenderCountModel.h"
#import "MNDInvestmentDetailViewController.h"
#import "UIView+JKFrame.h"
#import "MNDLoginUserModel.h"
@interface MNDInvestmentRecordViewController () <UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate, UITableViewDelegate, MNDInvestmentRecordListDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headerHeightonstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headerTopSpace;

/*! 指示器所在的容器 */
@property (weak, nonatomic) IBOutlet UIView *indicatorContainerView;
/*! 指示器 指示当前所选择的view */
@property (weak, nonatomic) IBOutlet UIView *indicatorView;
//选择器的item
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *segmentButtons;
//指示器的左边约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *indicatorLeadingConstraint;
//容器  需要在storyboard或者在viewWidLoad里设置pageViewController的transaction style为Scroll
@property (strong, nonatomic) MNDInvestmentRecordListContainerViewController *pageViewController;
//保存分页的数组
@property (strong, nonatomic) NSMutableArray *pageContentControllers;
//YES表示通过选择按钮切换页面，NO表示通过滑动切换页面
@property (assign, nonatomic) BOOL isManuallSegmentSelect;
@property (assign, nonatomic) BOOL isGotoRighPlace;
@property (assign, nonatomic) BOOL changedController;
@property (assign, nonatomic) BOOL userDraggingStartedTransitionInProgress;

@property (assign, nonatomic) NSInteger currentIndexController;
@property (assign, nonatomic) NSInteger nextIndexController;

/*! 头部view */
@property (weak, nonatomic) IBOutlet UIView *headerView;
/*! 头部背景图 */
@property (weak, nonatomic) IBOutlet UIImageView *headerImageView;
/*! 待收本金title */
@property (weak, nonatomic) IBOutlet UILabel *waitTotalMoneyTitleLabel;
/*! 代收本金 */
@property (weak, nonatomic) IBOutlet UILabel *waitTotalMoneyLabel;
/*! 待收收益title */
@property (weak, nonatomic) IBOutlet UILabel *waitEarningsTitleLabel;
/*! 待收收益 */
@property (weak, nonatomic) IBOutlet UILabel *waitEarningsLabel;
/*! 已收收益title */
@property (weak, nonatomic) IBOutlet UILabel *currentEarningsTitleLabel;
/*! 已收收益 */
@property (weak, nonatomic) IBOutlet UILabel *currentEarningsLabel;

//头部最大高度
@property (nonatomic) CGFloat headerMaxHeight;
//头部最小高度
@property (nonatomic) CGFloat headerMinHeight;

@end

@implementation MNDInvestmentRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showInvestDetail];
    self.leftBarTintColor = [UIColor whiteColor];
    self.barTitleColor = [UIColor whiteColor];
    self.naviBarTranslucent = YES;
    //头部的高度根据背景图确定
    UIImage *headerImage = [UIImage imageNamed:@"investment_racord_header_big"];
//    NSLog(@"height: %f", kScreenHeight);
    if (kScreenHeight >= 812) { //iPhone X
        self.headerHeightonstraint.constant = headerImage.size.height + 40;
    } else {
        self.headerHeightonstraint.constant = headerImage.size.height;
    }
    
    self.headerMaxHeight = self.headerHeightonstraint.constant;
    
    UIImage *headerSmallImage = [UIImage imageNamed:@"investment_racord_header_small"];
    self.headerMinHeight = headerSmallImage.size.height;
    
    [self initialPageViewControllers];
    
    [self makeHeaderContentsInitialConstraints];
    [self.view layoutIfNeeded];
    [self.view setNeedsLayout];
    
    if (self.shouldCustomBack) {
        [self customBackBarButton];
    }
}

- (void)showInvestDetail {
    if (self.tenderId != nil) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"InvestmentRecord" bundle:nil];
        MNDInvestmentDetailViewController *investmentDetailVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDInvestmentDetailViewController"];
        investmentDetailVC.tenderId = self.tenderId;
        investmentDetailVC.allowTransfer = YES;
        investmentDetailVC.hidesBottomBarWhenPushed = YES;
//        investmentDetailVC.shouldCustomBack = YES;
        [self.navigationController pushViewController:investmentDetailVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadTenderCounts];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
//    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

- (void)customBackBarButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
    
}

- (void)backAction:(id)sender {
    [self.tabBarController setSelectedIndex:3];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark -- 头部约束
//设置头部内容的初始位置
- (void)makeHeaderContentsInitialConstraints {
    self.waitTotalMoneyLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:36];
    CGFloat edgeMargin = 16.0;
    WeakSelf(self);
    [self.waitTotalMoneyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(weakself.headerView).offset(edgeMargin);
        make.centerY.equalTo(weakself.headerView);
    }];
    
    [self.waitTotalMoneyTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakself.waitTotalMoneyLabel.mas_top);
        make.leading.equalTo(weakself.waitTotalMoneyLabel);
    }];
    
    [self.waitEarningsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(weakself.headerView).offset(edgeMargin);
        make.bottom.equalTo(weakself.headerView.mas_bottom).offset(-25.0);
    }];
    [self.waitEarningsTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakself.waitEarningsLabel.mas_top);
        make.leading.equalTo(weakself.waitEarningsLabel);
    }];
    
    [self.currentEarningsTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakself.headerView).offset(30.0);
        make.centerY.equalTo(weakself.waitEarningsTitleLabel);
    }];
    
    [self.currentEarningsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(weakself.currentEarningsTitleLabel);
        make.centerY.equalTo(weakself.waitEarningsLabel);
    }];
}
//设置头部内容位置
- (void)remakeHeaderContentsInitialConstraints {
    self.waitTotalMoneyLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:19];
    CGFloat edgeMargin = 16.0;
    WeakSelf(self);
    [self.waitTotalMoneyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(weakself.headerView).offset(edgeMargin);
        make.bottom.equalTo(weakself.headerView).offset(-10);
    }];
    
    [self.waitTotalMoneyTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakself.waitTotalMoneyLabel.mas_top);
        make.leading.equalTo(weakself.waitTotalMoneyLabel);
    }];
    
    [self.waitEarningsTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakself.headerView);
        make.centerY.equalTo(weakself.waitTotalMoneyTitleLabel);
    }];
    [self.waitEarningsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(weakself.waitEarningsTitleLabel);
        make.centerY.equalTo(weakself.waitTotalMoneyLabel);
    }];

    NSDictionary *titleAtrrs = @{NSFontAttributeName : [UIFont fontWithName:@"PingFangSC-Regular" size:12]};
    CGSize titleSize = [weakself.currentEarningsTitleLabel.text sizeWithAttributes:titleAtrrs];
    
    NSDictionary *attrs = @{NSFontAttributeName : [UIFont fontWithName:@"PingFangSC-Regular" size:19]};
    CGSize size = [weakself.currentEarningsLabel.text sizeWithAttributes:attrs];
    
    [self.currentEarningsTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(weakself.waitEarningsTitleLabel);
        
        //如果title的宽度大于金额的宽度，以title右边距为准
        if (titleSize.width >= size.width) {
            make.trailing.equalTo(weakself.headerView).offset(-edgeMargin);
        } else {
            make.leading.equalTo(weakself.currentEarningsLabel);
        }
    }];
    
    [self.currentEarningsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.centerY.equalTo(weakself.waitEarningsLabel);
        if (titleSize.width > size.width) {
            make.leading.equalTo(weakself.currentEarningsTitleLabel);
        } else {
            make.trailing.equalTo(weakself.headerView).offset(-edgeMargin);
        }
    }];
}

- (void)loadTenderCounts {
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_USER_TENDER_COUNT parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            MNDUserTenderCountModel *model = [MNDUserTenderCountModel mj_objectWithKeyValues:responseModel.data];
            
            [weakself configHeaderContents:model];
        } else {
            NSDictionary *dict = responseModel.msg;
            
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据出错了"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configHeaderContents:(MNDUserTenderCountModel *)model {
    self.waitTotalMoneyLabel.text = model.currentTenderAmount;
    self.waitEarningsLabel.text = model.waitInterestAmount;
    self.currentEarningsLabel.text = model.interestAmount;
}

#pragma MNDInvestmentListViewController Delegate

- (void)recordListDidSelectRowWithModel:(MNDInvestmentRecordModel *)recordModel {
    [self performSegueWithIdentifier:[MNDInvestmentDetailViewController description] sender:recordModel.tenderId];
}

- (void)recordListDidScroll:(UIScrollView *)scrollView withTotalnum:(NSInteger)totalnum {
    
    //向上滚动
    if (scrollView.contentOffset.y > 0 && totalnum > 2) {
        
        self.headerImageView.image = [UIImage imageNamed:@"investment_racord_header_small"];
        
        if (self.headerHeightonstraint.constant > self.headerMinHeight) {
            
            self.headerHeightonstraint.constant -= scrollView.contentOffset.y;
            [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, 0)];
        } else {
            self.headerHeightonstraint.constant = self.headerMinHeight;
        }
//        NSLog(@"----%lf", self.waitTotalMoneyLabel.jk_bottom - self.waitEarningsTitleLabel.jk_top);
        if (self.waitEarningsTitleLabel.jk_top - self.waitTotalMoneyLabel.jk_bottom <= 2) {
            [self remakeHeaderContentsInitialConstraints];
        }
    }
    
    //向下滚动
    if (scrollView.contentOffset.y < 0 && totalnum > 2) {
        
        self.headerImageView.image = [UIImage imageNamed:@"investment_racord_header_big"];
        
        if (self.headerHeightonstraint.constant < self.headerMaxHeight) {
            self.headerHeightonstraint.constant -= scrollView.contentOffset.y;
            [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, 0)];
        } else {
            self.headerHeightonstraint.constant = self.headerMaxHeight;
        }
        CGFloat height = 20;
        if (kScreenHeight >= 812) {
            height = 60;
        }
        if (self.waitEarningsTitleLabel.jk_top > self.headerView.jk_centerY + height) {
            [self makeHeaderContentsInitialConstraints];
        }
    }
}




#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:[MNDInvestmentDetailViewController description]]) {
        MNDInvestmentDetailViewController *detailVC = segue.destinationViewController;
        detailVC.tenderId = sender;
    }
}


#pragma mark - 配置左右列表

//配置左右切换的列表VC
- (void)initialPageViewControllers {
    //配置所有两个列表的VC
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"InvestmentRecord" bundle:nil];
    MNDInvestmentRecordListViewController *leftVC = [storyboard instantiateViewControllerWithIdentifier:[MNDInvestmentRecordListViewController description]];
    leftVC.listStyle = RecordListStyleInTender;
    
    MNDInvestmentRecordListViewController *rightVC = [storyboard instantiateViewControllerWithIdentifier:[MNDInvestmentRecordListViewController description]];
    rightVC.listStyle = RecordListStyleEnd;
    
    
    //将controller加入数组中
    [self.pageContentControllers addObject:leftVC];
    [self.pageContentControllers addObject:rightVC];
    
    //把ContainerViewController变成PageViewController
    self.pageViewController = self.childViewControllers[0];
    self.pageViewController.dataSource = self;
    self.pageViewController.delegate = self;
    [self.pageViewController setViewControllers:@[self.pageContentControllers.firstObject]
                                      direction:UIPageViewControllerNavigationDirectionForward
                                       animated:YES
                                     completion:^(BOOL finished) {
                                         
                                     }];
    
    for (UIView *subView in self.pageViewController.view.subviews) {
        if ([subView isKindOfClass:[UIScrollView class]]) {
            ((UIScrollView *)subView).delegate = self;
        }
    }
    
//    //**-------以上是通用配置
    leftVC.delegate = self;
    rightVC.delegate = self;
}

#pragma mark - 跳转

#pragma mark - UIPageViewControllerDataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    
    for (NSInteger i = 0; i < self.pageContentControllers.count - 1; i++) {
        if (viewController == [self.pageContentControllers objectAtIndex:i]) {
            return [self.pageContentControllers objectAtIndex:i + 1];
        }
    }
    
    return nil;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    for (NSInteger i = self.pageContentControllers.count - 1; i > 0; i--) {
        if (viewController == [self.pageContentControllers objectAtIndex:i]) {
            
            return [self.pageContentControllers objectAtIndex:i - 1];
        }
    }
    return nil;
}
#pragma mark - UIPageViewControllerDelegate

- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    
    if (pendingViewControllers.count > 0) {
        self.nextIndexController = [self checkIndexOfController:[pendingViewControllers firstObject]];
    }
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (completed) {
        if (self.nextIndexController != -1) {
            self.currentIndexController = self.nextIndexController;
        }
        self.changedController = YES;
    }
    if (finished) {
        
    }
}

#pragma mark - UIScrollView Delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.isTracking || scrollView.isDecelerating) {
        self.userDraggingStartedTransitionInProgress = YES;
    }
    
    CGPoint point = scrollView.contentOffset;
    
    float percentComplete;
    percentComplete = fabs(point.x - self.view.frame.size.width)/self.view.frame.size.width;
    
    if (self.isManuallSegmentSelect) {
        
        if (percentComplete == 1.0) {
            self.isGotoRighPlace = YES;
            self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.nextIndexController;
        }
        
        if (!self.isGotoRighPlace) {
            NSInteger changeIndex;
            if (self.nextIndexController > self.currentIndexController) {
                changeIndex = self.nextIndexController - self.currentIndexController;
            } else {
                changeIndex = self.currentIndexController - self.nextIndexController;
            }
            
            if (self.nextIndexController > self.currentIndexController || self.nextIndexController == self.pageContentControllers.count - 1) {
                self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete * changeIndex  + self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController;
            } else {
                self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController - self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete * changeIndex;
            }
        }
        
    } else {
        CGFloat widthSegment = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count;
        
        if (percentComplete * widthSegment > widthSegment / 2) {
            [self changeSelectedButtonToIndex:self.nextIndexController];
        }
        
        if (self.changedController) {
            self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController;
            self.changedController = NO;
        } else  {
            if (self.nextIndexController > self.currentIndexController || self.nextIndexController == self.pageContentControllers.count - 1) {
                self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete + self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController;
            } else {
                self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController - self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete;
            }
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.userDraggingStartedTransitionInProgress = NO;
}

#pragma mark - Action
//需要在storyboard设置button的tag值，或者在viewDidLoad设置
- (IBAction)tappSegmentAction:(UIButton *)sender {
    NSInteger index = sender.tag % 100;
    if (self.currentIndexController == index) {
        return;
    }
    
    if (self.userDraggingStartedTransitionInProgress) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    UIPageViewControllerNavigationDirection direction;
    if (index > self.currentIndexController) {
        direction = UIPageViewControllerNavigationDirectionForward;
    }else{
        direction = UIPageViewControllerNavigationDirectionReverse;
    }
    
    self.isManuallSegmentSelect = YES;
    self.nextIndexController = index;
    
    id controller = self.pageContentControllers[index];
    NSArray *viewControllers = @[controller];
    [self.pageViewController setViewControllers:viewControllers direction:direction animated:YES completion:^(BOOL finished) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.currentIndexController = weakSelf.nextIndexController;
            [weakSelf changeSelectedButtonToIndex:weakSelf.currentIndexController];
            weakSelf.isGotoRighPlace = NO;
            weakSelf.isManuallSegmentSelect = NO;
        });
    }];
}

#pragma mark - Utility

- (NSInteger)checkIndexOfController:(UIViewController *)controller  {
    for (NSInteger i = 0; i < self.pageContentControllers.count; i++) {
        if (controller == [self.pageContentControllers objectAtIndex:i]) {
            return i;
        }
    }
    
    return -1;
}

- (void)changeSelectedButtonToIndex:(NSInteger)index {
    for (UIButton *button in self.segmentButtons) {
        if (button == [self.segmentButtons objectAtIndex:index]) {
            [button setSelected:YES];
        } else {
            [button setSelected:NO];
        }
    }
}

#pragma mark - gettter

- (NSMutableArray *)pageContentControllers {
    if (!_pageContentControllers) {
        _pageContentControllers = [NSMutableArray array];
    }
    
    return _pageContentControllers;
}

@end
